<template>
  <!--班级-->
  <div class="class">
    <!--过滤器-->
    <div class="filter-container">
      <div class="filter-item item-input">
        <el-input v-model="condition.className" placeholder="请输入班级名称"></el-input>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="searchClass"><i class="el-icon-search"></i> 搜索</el-button>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="freshClass"><i class="el-icon-refresh"></i> 刷新</el-button>
      </div>
    </div>
  </div>
  <!--班级列表，分页处理-->
  <div class="class-list">
    <el-table
        :data="classTable"
        v-loading= classTableOk
        border
        style="width: 100%">
      <el-table-column
          label="序号"
          width="80"
          align="center">
        <template v-slot="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column
          prop="className"
          label="班级名称"
          width="280"
          align="center">
        <template v-slot="scope">
          <el-tooltip  effect="light" content="查看该考试班的学生" placement="top">
            <span class="col2-cell-style" @click="viewClass(scope.$index)">{{scope.row.className}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
          prop="companyId"
          label="公司名称"
          width="180"
          align="center">
      </el-table-column>
      <el-table-column
          prop="creatorId"
          label="创建人"
          width="180"
          align="center">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          align="center">
      </el-table-column>
      <el-table-column
          prop="modifyTime"
          label="最后修改时间"
          width="180"
          align="center">
      </el-table-column>
      <el-table-column
          prop="disabled"
          label="状态"
          align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.disabled === false" type="success" disable-transitions>正常</el-tag>
          <el-tag v-if="scope.row.disabled === true" type="danger" disable-transitions>禁用</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <Pagination :currentPage="pagination.currentPage" :pageSize="pagination.pageSize" :total="pagination.totalCount"
              @changePage="handlePageChange" ></Pagination>

  <!--考试班详情-->
  <el-dialog title="查看考试班学生详情" v-model="toViewStudent" fullscreen :before-close="toViewStudentClose" >
    <!--过滤栏-->
    <div class="filter-bar">
      <el-input
          placeholder="请输入名称搜索"
          v-model="eidInput"
          clearable
          class="filter-item">
      </el-input>
      <el-button type="primary" class="filter-item" @click="searchStudentsById()">
        <i class="el-icon-search "></i> 搜索
      </el-button>
      <el-button type="primary" class="filter-item item-margin-left-16"
                 @click="viewClass(curIndex), eidInput = ''">
        <i class="el-icon-refresh"></i> 刷新
      </el-button>
      <el-button type="primary" class="filter-item item-margin-left-16" @click="toViewStudent = false">
        <i class="el-icon-circle-close"></i> 关闭页面
      </el-button>
    </div>

    <!--学生表格-->
    <el-table
        :data="studentDetail"
        border
        style="width: 100%"
        id="exportTable">
      <el-table-column
          label="序号"
          width="100"
          align="center">
        <template #default="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column
          label="学号"
          prop="userId"
          width="320"
          align="center">
      </el-table-column>
      <el-table-column
          label="姓名"
          prop="userName"
          width="320"
          align="center">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          align="center">
        <el-tag disable-transitions>正常</el-tag>
      </el-table-column>
    </el-table>

    <!--分页-->
    <Paginationz :currentPage="stuCurPage" :pageSize="stuPageSize"
                 :total="stuTotal"
                 :handleSizeChange="handleSizeChange2" :handleCurrentChange="handleCurrentChange2"></Paginationz>

  </el-dialog>

</template>

<script>
import API from "@/api/examClass"
import Pagination from "@/components/Paginationz.vue"
import Paginationz from '@/components/PaginationNew.vue'
import { ElMessage } from 'element-plus';
export default {

  // import 引入的组件需要注入到对象中才能使用
  props: {},
  components:{Pagination,Paginationz},
  data () {
    // 这里存放数据
    return {
      classTableOk: true,
      //分页信息
      pagination: {
        currentPage: 1, //初始页
        pageSize: 10, //每页的数据
        totalCount: 0 //总数据
      },
      // 创建班级弹窗
      toCreateClass : false,
      classForm: { // 班级表单
        name: ''
      },
      formLabelWidth: '120px',
      // 删除班级弹窗
      toDeleteClass : false,
      toDeleteStudent: false,
      // 查看班级弹窗
      currClass : -1,
      toViewStudent : false,
      studentDetail : [],
      stuCurPage : 1,
      stuPageSize : 20,
      stuTotal:0,
      AddstudentRule :{
        phone: [{required: true, message: '不可为空', trigger: 'blur'},
        ],
      },
      Addstudent :{
        way: '1',
        phone:''
      },
      //搜索
      eidInput : '',
      IsSearch : false,
      //查看班级的内部弹窗
      innerVisible : false,
      innerVisible2 : false,
      //修改班级弹窗
      toChangeClassName: false,
      changeName:'',
      // 班级表格请求
      params:{
        "condition": {
          "className": null
        },
        "paging": {
          totalCount: 100,
          pageIndex: 1,
          pageSize: 10,
          enableTotalCount: true
        },
        sorts: [],
        extras: {}
      },

      //  班级相关内容
      class:{
        id: 0,
        className: "",
        creatorId: 0,
        companyId: 0,
        createTime: "",
        modifyTime: "",
        disabled: false
      },
      classTable:[],
      curClassIndex: 0, //选中的班级
      //  班级排序信息
      sorts:[],
      sortParam:{
        // Ascending Descending
        mode: "Ascending",
        fields:[]
      },
      //  搜索其他信息
      condition:{
        className:""
      },
      extras:{
        key:"",
      },
      //现在选中的考试班级下标
      curIndex: 0,
      oldStudentNum :[],
      //用于添加学生的班级表
      innerVisible: false,
      currentGPage: 1,
      pageGSize : 20,
      tclassDetail:[],
      currTClass: 0,
      studentTDetail:[],
      stuTTotal: 0,
      stuTCurPage : 1,
      stuTPageSize: 20,
      //全选的班级
      selectClass:[],
      selectClassLenght:0,
      selectClassnum:[],
      studentADetail:[],
      curStudentId: 0,
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {},
  // 方法集合
  methods: {
    handlePageChange(pageSize,currentPage){
      this.pagination.pageSize=pageSize
      this.pagination.currentPage=currentPage
      this.params.paging.pageSize=pageSize
      this.params.paging.pageIndex=currentPage
      this.getClassTable()
    },
    freshClass(){
      this.$router.go(0)
    },
    async getUserInfo(param) {
      try {
        console.log(param)
        const res2 = await API.getUserInfo(param);
        console.log(res2.data);
        if (res2.data.success === true) {
          if (res2.data.content.records.length === 0) {
            this.$message.error("请求创建人失败");
          } else {
            return res2.data.content.records[0].username;
          }
        }
      } catch (error) {
        console.log(error)
        this.$message.error("请求失败");
      }
    },

    async getClassTable() {
      this.classTableOk = true;
      console.log("this.params:", this.params);
      try {
        const res = await API.getAllExamClass(this.params);
        if (res.data.success === true) {
          this.pagination.totalCount = res.data.totalCount;
          const res1 = await API.getAllCompany();
          if (res1.data.success === true) {
            this.classTable = res.data.data;
            for (let i = 0; i < res.data.data.length; i++) {
              this.classTable[i].companyId = res1.data.content[res.data.data[i].companyId - 1].name;
              const param = res.data.data[i].creatorId;
              let username = await this.getUserInfo(param);
              this.classTable[i].creatorId = username
              // 从getUserInfo函数中获取到的username可以在这里使用
            }
          }
          this.$message.success("获取班级信息成功");
        } else {
          console.log(res.data);
          this.$message.error("获取班级信息失败，请联系管理员");
        }

        this.classTableOk = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 初始化分页信息
    init(){
      let  paging1={
        totalCount: 0,
        pageIndex: 1,
        pageSize: 10,
        enableTotalCount: true
      }
      this.paging=paging1
    },
    searchClass(){
      this.init()
      this.searchClassTable()
    },

    // 搜索班级
    async searchClassTable(){

      let searchClassTableparams = {
        "condition": {
          "className":  this.condition.className.trim()
        },
        "paging": {
          "paging": this.paging1
        },
      }
      this.classTableOk = true;
      try {
        const res = await API.getAllExamClass(searchClassTableparams);
        if (res.data.success == true) {
          this.pagination.totalCount = res.data.totalCount;
          const res1 = await API.getAllCompany();
          if (res1.data.success == true) {
            this.classTable = res.data.data;
            for (let i = 0; i < res.data.data.length; i++) {
              this.classTable[i].companyId = res1.data.content[res.data.data[i].companyId - 1].name;
              const param = res.data.data[i].creatorId;
              let username = await this.getUserInfo(param);
              this.classTable[i].creatorId = username
              // 从getUserInfo函数中获取到的username可以在这里使用
            }
          }

          this.$message.success("获取班级信息成功");
        } else {
          console.log(res.data);
          this.$message.error("获取班级信息失败，请联系管理员");
        }

        this.classTableOk = false;
      } catch (error) {
        console.log(error);
      }
    },
    //搜索学生
    searchStudentsById(){
      this.IsSearch = true
      this.viewClass(this.curIndex)
    },
    // 查看班级学生
    viewClass(index){
      // console.log(this.classTable[index].id)
      this.currClass  = this.classTable[index].id
      this.curIndex = index
      let getExamClassStudentparams ={
        "condition": {
          "classId": this.currClass
        },
        "paging": {
          "pageIndex": this.stuCurPage,
          "pageSize": this.stuPageSize,
          "enableTotalCount": true
        }
      }
      if(this.IsSearch === true){
        getExamClassStudentparams ={
          "condition": {
            "classId": this.currClass,
            "userName" : this.eidInput.trim()
          },
          "paging": {
            "pageIndex": this.stuCurPage,
            "pageSize": this.stuPageSize,
            "enableTotalCount": true
          }
        }
      }
      API.getExamClassStudent(getExamClassStudentparams).then(res=>{

        if(res.data.success===true){
          console.log(res.data)
          // 渲染表格
          this.studentDetail = res.data.data
          this.stuTotal = res.data.totalCount
          this.$message.success("获取班级学生信息成功")
          this.toViewStudent= true
        }else {
          console.log(res.data)
          this.$message.error("获取班级学生信息失败，请联系管理员")
        }

      }).catch(e=>{
        console.log(e)
      })
    },
    //检测到关闭
    toViewStudentClose(){
      this.eidInput = ''
      this.toViewStudent = false;
    },



    preDelClass(index) {
      this.curClassIndex = index;
      console.log(index)
      this.toDeleteClass = true;
    },
    //翻页考试学生表
    handleCurrentChange2(val) {
      this.stuCurPage = val;
      this.viewClass(this.curIndex)
    },
    handleSizeChange2(val){
      this.stuPageSize = val;
      this.viewClass(this.curIndex)
    },
    // 获取所有培训班级
    getTrainClass(){
      API.getAllTrainClass().then(res=>{
        if(res.data.success===true){
          console.log(res.data)
          this.$message.success("请求所有班级成功")
          this.tclassDetail = res.data.content
        }else {
          console.log(res.data)
          this.$message.error("请求班级失败，请联系管理员")
        }
        // this.classTable=res.data
      }).catch(e=>{
        console.log(e)
      })
    },
    //查看培训班级的学生
    viewNClassByEClass(index){
      console.log(this.tclassDetail[index].id)
      this.currTClass = this.tclassDetail[index].id//现在的班级号
      let getOneTrainClassParams = {
        "trainClassId": this.currTClass
      }
      API.getOneTrainClass(getOneTrainClassParams).then(res=>{
        if(res.data.success===true){
          console.log(res.data)
          for(let i = 0;i<res.data.content.length;i++){
            res.data.content[i].className = this.tclassDetail[index].name
          }
          this.studentTDetail = [...this.studentTDetail,...res.data.content]
          this.stuTTotal = this.studentTDetail.length
          this.stuTCurPage = 1
          this.combineStudent()
          this.$message.success("添加班级成功")
        }else {
          console.log(res.data)
          this.$message.error("添加班级失败，请联系管理员")
        }
      }).catch(e=>{
        console.log(e)
      })
    },
    clearClass(row){
      let delId = row.id
      let detail = this.studentTDetail
      this.studentTDetail = detail.filter(function(detail){
        return detail.classId != delId
      })
      this.stuTTotal =this.studentTDetail.length
    },



  },
  // 生命周期 - 创建完成（可以访问当前this 实例）
  setup () {
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {
    this.getClassTable()
  },
  onBeforeMount () {
  }, // 生命周期 - 挂载之前
  onBeforeUpdate () {
  }, // 生命周期 - 更新之前
  onUpdated () {
  }, // 生命周期 - 更新之后
  onBeforeUnmount () {
  }, // 生命周期 - 销毁之前
  onUnmounted () {
  }, // 生命周期 - 销毁完成
  onErrorCaptured () {
  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped>



input[type=file] {
  display: none !important;
}

.class {
  width: 100%;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.item-input {
  width: 200px;
  margin-right: 5px;
}

.filter-item:nth-child(3), .filter-item:nth-child(4) {
  margin-left: 16px;
}

.class-list {
  width: 100%;
}

.el-dialog .el-form-item {
  font-weight: 600;
}

.dialog-body-info .upload-box {
  width: 94.5%;
  height: 120px;
  margin-left: 5%;
  margin-bottom: 20px;
  font-weight: 100;
  border: 2px #bbb dashed;
  border-radius: 8px;
  display: flex;
  align-items: center;

}

.dialog-body-info .upload-content {
  margin: 0 auto;
}

.dialog-body-info .upload-content .file-upload {
  display: inline-block;
  margin-left: 1rem;
}

.dialog-body-info .upload-content span {
  font-size: 1.5rem;
  color: darkgrey;
}

.upload-tip a {
  text-decoration: none;
  color: #409EFF;
}

.upload-tip {
  margin-top: 10px;
}

.dialog-body-table .el-table {
  margin-top: 20px;
}

.dialog-body-save h3 span {
  color: green;
}

.dialog-body-save h3 a {
  text-decoration: none;
  color: inherit;
}

.class-list .col2-cell-style, .upload-tip span {
  color: #409EFF;
  cursor: pointer;
}

</style>
